package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {
    private String name;  // 锁的名字
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:";  // 锁名前缀

    // 静态常量
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";  // ID前缀
    // 静态代码块
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unLock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    // 有参构造
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    // 获取锁
    @Override
    public boolean tryLock(long timeoutSec) {
        // 标识: UUID-线程ID
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
//        return success; // 自动拆箱过程，有安全风险，如果是 null 就空指针
        return Boolean.TRUE.equals(success); // 避免空指针的可能性风险
    }

    // 释放锁
    @Override
    public void unlock() {
        String threadId = ID_PREFIX + Thread.currentThread().getId();
//        String nowId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//
//        if (threadId.equals(nowId)) {
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//        }

        // TODO 基于 Lua 脚本实现分布式锁的释放逻辑
        // 参数：脚本、key、argv
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+ name),
                threadId);
    }
}
